<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" destroyOnClose showFooter :title="getTitle" :width="drawerWith" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, unref } from 'vue';
import { BasicForm, useForm } from '@apps/antd-admin/src/components/Form/index';
import { BasicDrawer, useDrawerInner } from '@apps/antd-admin/src/components/drawer';
import { changeTypeFormSchema } from '../data/data';
import { Api } from '../data/api';
import { useAppInject } from '@apps/antd-admin/src/hooks/web/use-app-inject';

const { getIsMobile } = useAppInject();
const drawerWith = ref('40%');
if (unref(getIsMobile)) {
  drawerWith.value = '80%';
}
// 声明Emits
const emit = defineEmits(['success', 'register']);
//是否是编辑模式
const isUpdate = ref(true);
//计算标题
const getTitle = '转抵扣类型';
//配置表单
const [registerForm, { resetFields, setFieldsValue, validate, saveOrUpdate }] = useForm({
  rowKey: 'fullDeductionDetailId',
  labelWidth: 180,
  labelCol: { span: 6 },
  saveApi: Api.changeDeductionType,
  updateApi: Api.changeDeductionType,
  schemas: changeTypeFormSchema,
});
//表单赋值
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async data => {
  setDrawerProps({ confirmLoading: false });
  await resetFields();
  isUpdate.value = !!data?.isUpdate;
  const record = data.record;
  if (isUpdate.value) {
    let newData = {
      fullDeductionDetailId: record.fullDeductionDetailId,
      fullDeductionId: record.fullDeductionId,
      vipCardNo: record.vipCardNo,
      fullDeductionDetailAmount: record.fullDeductionDetailAmount,
      fullDeductionType: String(record.fullDeductionType),
    };
    await setFieldsValue(newData);
  }
});

/**
 * 表单提交
 */
async function handleSubmit() {
  try {
    setDrawerProps({ confirmLoading: true });
    await saveOrUpdate(emit);
    closeDrawer();
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
